/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.test.app.controller;

import com.test.app.email.Email;
import com.test.app.form.Contact;
import com.test.app.service.ContactService;
import com.test.app.validator.ContactValidator;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

/**
 *
 * @author darshana
 */
@Controller
@SessionAttributes
public class ContactController {

    @Autowired
    private ContactService contactService;
    @Autowired
    private ContactValidator contactValidator;
    @Autowired
    private Email email;

    @Autowired
    public ContactController(ContactService contactService, ContactValidator contactValidator) {
        this.contactService = contactService;
        this.contactValidator = contactValidator;
    }

    @RequestMapping(value = "/contact", method = RequestMethod.GET)
    public String showContact(Model model) {
        List contact = contactService.list();
//        to show contact
        model.addAttribute(contact);
        //for new contact
        Contact c = new Contact();


        model.addAttribute(c);

//        map.put("contact",new Contact());
//        map.put("contactList", contactService.list());
//        Contact contact = new Contact();
//        model.put("contact", contact);
        return "contact";
    }

    @RequestMapping(value = "/addContact", method = RequestMethod.POST)
    public String addContact(@Valid @ModelAttribute("contact")Contact contact, BindingResult result) {
        

        if (result.hasErrors()) {
            
            System.out.println("got errors");
            
            return "contact";
        } else {
            contactService.addContact(contact);
            return "redirect:/contact";
        }
    }

    @RequestMapping(value = "/delete/{contactId}")
    public String deleteContact(@PathVariable("contactId") Integer contactId) {
        contactService.remove(contactId);
        return "redirect:/contact";
    }

    @RequestMapping(value = "/email")
    public String sendEmail() throws Exception {
        email.sendEmail();



        //        map.put("contact",new Contact());
//        map.put("contactList", contactService.list());
//        Contact contact = new Contact();
//        model.put("contact", contact);
        return "contact";

    }
}
